<template>
  <!-- 发起人 -->
  <div class="node-wrap" v-if="nodeConfig.type !== 4">
    <div
      class="node-wrap-box"
      :class="{ 'start-node': nodeConfig.type === 0, 'active error': isTried && nodeConfig.error }"
    >
      <div
        class="title"
        :style="
          'background: rgb(' +
          ['87, 106, 149', '255, 148, 62', '50, 150, 250'][nodeConfig.type] +
          ');'
        "
        @click="clickEvent('')"
      >
        <span v-show="nodeConfig.type === 1">
          <Icon class="iconfont" icon="bxs:user" size="12" />
        </span>
        <span v-show="nodeConfig.type === 2">
          <Icon class="iconfont" icon="ep:promotion" size="12" />
        </span>
        <span v-if="nodeConfig.type === 0">{{ nodeConfig.nodeName }}</span>
        <span class="editable-title" v-if="nodeConfig.type !== 0 && !state.isInput">
          {{ nodeConfig.nodeName }}
        </span>
        <Input
          v-if="nodeConfig.type !== 0 && state.isInput"
          class="editable-title-input"
          v-focus
          v-model:value="nodeConfig.nodeName"
          :placeholder="state.placeholderList[nodeConfig.type]"
          @blur="blurEvent('')"
        />
        <span class="close" v-if="nodeConfig.type !== 0 && !state.isInput" @click="delNode">
          <Icon size="14" icon="ant-design:close-outlined" />
        </span>
      </div>
      <div class="content">
        <!-- 发起人 -->
        <div class="truncate" v-if="nodeConfig.type == 0">
          {{ arrToStr(flowPermission) ? arrToStr(flowPermission) : '所有人' }}
        </div>
        <!-- 审批人 -->
        <div class="truncate" v-if="nodeConfig.type == 1">
          <span class="placeholder">请选择{{ state.placeholderList[nodeConfig.type] }}</span>
        </div>
        <!-- 抄送人 -->
        <div class="truncate" v-if="nodeConfig.type == 2">
          <span class="placeholder">请选择{{ state.placeholderList[nodeConfig.type] }}</span>
        </div>
        <div><Icon icon="ant-design:right-outlined" /></div>
      </div>
      <div class="error_tip" v-if="isTried && nodeConfig.error && nodeConfig.type !== 0">
        <Tooltip>
          <template #title>未选择{{ state.placeholderList[nodeConfig.type] }}</template>
          <Icon icon="ci:error-outline" color="rgb(242, 86, 67)" size="30" />
        </Tooltip>
      </div>
    </div>
    <AddNode v-model:childNode="nodeConfig.childNode" />
  </div>

  <!-- 添加条件node -->
  <div class="branch-wrap" v-if="nodeConfig.type === 4">
    <div class="branch-box-wrap">
      <div class="branch-box">
        <button class="add-branch" @click="addTerm">添加条件</button>
        <div class="col-box" v-for="(item, index) in nodeConfig.conditionNodes" :key="index">
          <div class="condition-node">
            <div class="condition-node-box">
              <div class="auto-judge" :class="{ 'error active': isTried && item.error }">
                <div class="title-wrapper">
                  <Input
                    class="editable-title-input"
                    v-focus
                    v-if="state.isInputList[index]"
                    v-model:value="item.nodeName"
                    placeholder="条件"
                    @blur="blurEvent(index)"
                  />
                  <span
                    class="editable-title"
                    v-if="!state.isInputList[index]"
                    @click="clickEvent(index)"
                  >
                    {{ item.nodeName }}
                  </span>
                  <span class="priority-title">优先级{{ item.priorityLevel }}</span>

                  <Tooltip>
                    <template #title>复制条件</template>
                    <Icon
                      class="copy"
                      icon="ant-design:copy-twotone"
                      color="rgba(25, 31, 37, 0.56)"
                      @click="copyTerm(index)"
                    />
                  </Tooltip>
                  <Icon
                    class="close"
                    icon="ant-design:close-outlined"
                    color="rgba(25, 31, 37, 0.56)"
                    @click="delTerm(index)"
                  />
                </div>
                <div class="content">{{ conditionStr(nodeConfig, index) }}</div>
                <!-- 左右箭头 -->
                <div
                  class="sort-right"
                  v-if="index !== nodeConfig.conditionNodes.length - 1"
                  @click="arrTransfer(index)"
                >
                  <Icon icon="ant-design:right-outlined" size="14" />
                </div>
                <div class="sort-left" v-if="index !== 0" @click="arrTransfer(index, -1)">
                  <Icon icon="ant-design:left-outlined" size="14" />
                </div>
                <div class="error_tip" v-if="isTried && item.error">
                  <Tooltip>
                    <template #title>未设置条件</template>
                    <Icon icon="ci:error-outline" color="rgb(242, 86, 67)" size="30" />
                  </Tooltip>
                </div>
              </div>
              <AddNode v-model:childNode="item.childNode" />
            </div>
          </div>
          <NodeWrap v-if="item.childNode && item.childNode" v-model:nodeConfig="item.childNode" />
          <div class="top-left-cover-line" v-if="index === 0"></div>
          <div class="bottom-left-cover-line" v-if="index === 0"></div>
          <div
            class="top-right-cover-line"
            v-if="index === nodeConfig.conditionNodes.length - 1"
          ></div>
          <div
            class="bottom-right-cover-line"
            v-if="index === nodeConfig.conditionNodes.length - 1"
          ></div>
        </div>
      </div>
      <AddNode v-model:childNode="nodeConfig.childNode" />
    </div>
  </div>

  <!-- 嵌套子节点 -->
  <NodeWrap v-if="nodeConfig.childNode" v-model:nodeConfig="nodeConfig.childNode" />
</template>

<script lang="tsx" setup name="NodeWrap">
  import { reactive, toRef, toRefs } from 'vue';
  import { Input, Tooltip } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { useWorkFlow } from '/@/store/modules/workFlow';
  import { arrToStr, conditionStr } from '/@/utils/func/index';
  import AddNode from './AddNode.vue';
  import type { IState } from './index';
  import { cloneDeep } from 'lodash-es';
  const props = defineProps({
    nodeConfig: {
      type: Object,
      default: () => {},
    },
  });
  const emit = defineEmits(['update:nodeConfig']);
  const nodeConfig = toRef(props, 'nodeConfig');
  const store = useWorkFlow();
  const { flowPermission, isTried } = toRefs(store);
  const state = reactive<IState>({
    placeholderList: ['发起人', '审核人', '抄送人'],
    // input 输入框列表 eg: [true, true, false, true]
    isInputList: [],
    // node 节点输入框状态
    isInput: false,
  });

  /**
   * 点击节点名称，输入框获取焦点
   * @param index 节点下标
   */
  const clickEvent = (index) => {
    if (index || index === 0) {
      state.isInputList[index] = true;
    } else {
      state.isInput = true;
    }
  };
  /**
   * 节点名称输入框失去焦点
   * @param index 节点下标
   */
  const blurEvent = (index) => {
    if (index || index === 0) {
      state.isInputList[index] = false;
      if (nodeConfig.value.conditionNodes) {
        nodeConfig.value.conditionNodes[index].nideName =
          nodeConfig.value.conditionNodes[index].nideName || '条件';
      }
    } else {
      state.isInput = false;
      nodeConfig.value.nodeName = nodeConfig.value.nodeName
        ? nodeConfig.value.nodeName
        : state.placeholderList[nodeConfig.value.type];
    }
  };
  /**
   * 删除当前节点
   */
  const delNode = () => {
    emit('update:nodeConfig', props.nodeConfig.childNode);
  };
  /**
   * 删除条件
   */
  const delTerm = (index) => {
    nodeConfig.value.conditionNodes.splice(index, 1);
    nodeConfig.value.conditionNodes.map((item, index) => {
      item.priorityLevel = index + 1;
      item.nodeName = `条件${index + 1}`;
    });
    for (let i = 0; i < nodeConfig.value.conditionNodes.length; i++) {
      nodeConfig.value.conditionNodes[i].error =
        conditionStr(nodeConfig.value, i) == '请设置条件' &&
        i != nodeConfig.value.conditionNodes.length - 1;
    }
    emit('update:nodeConfig', nodeConfig.value);
    if (nodeConfig.value.conditionNodes.length == 1) {
      if (nodeConfig.value.childNode) {
        if (
          nodeConfig.value.conditionNodes &&
          nodeConfig.value.conditionNodes.length &&
          nodeConfig.value.conditionNodes[0].childNode
        ) {
          reData(nodeConfig.value.conditionNodes[0].childNode, nodeConfig.value.childNode);
        } else {
          nodeConfig.value.conditionNodes[0].childNode = nodeConfig.value.childNode;
        }
      }
      emit('update:nodeConfig', nodeConfig.value.conditionNodes[0].childNode);
    }
  };
  /**
   * 复制条件
   */
  const copyTerm = (index) => {
    const copy = cloneDeep(nodeConfig.value.conditionNodes[index]);
    copy.nodeName = `${copy.nodeName} (复制)`;
    nodeConfig.value.conditionNodes.splice(index + 1, 0, copy);
    nodeConfig.value.conditionNodes.map((v, i) => {
      v.priorityLevel = i + 1;
    });
    emit('update:nodeConfig', nodeConfig.value);
  };
  const reData = (data, addData) => {
    if (!data.childNode) {
      data.childNode = addData;
    } else {
      reData(data.childNode, addData);
    }
  };
  /**
   * 条件分支箭头切换优先级（顺序）
   */
  const arrTransfer = (index, type = 1) => {
    //向左-1,向右1
    nodeConfig.value.conditionNodes[index] = nodeConfig.value.conditionNodes.splice(
      index + type,
      1,
      nodeConfig.value.conditionNodes[index],
    )[0];
    nodeConfig.value.conditionNodes.map((item, index) => {
      item.priorityLevel = index + 1;
    });
    for (let i = 0; i < nodeConfig.value.conditionNodes.length; i++) {
      nodeConfig.value.conditionNodes[i].error =
        conditionStr(nodeConfig.value, i) == '请设置条件' &&
        i != nodeConfig.value.conditionNodes.length - 1;
    }
    emit('update:nodeConfig', nodeConfig.value);
  };
  /**
   * 添加条件
   */
  const addTerm = () => {
    let len = nodeConfig.value.conditionNodes.length + 1;
    nodeConfig.value.conditionNodes.push({
      nodeName: '条件' + len,
      type: 3,
      priorityLevel: len,
      conditionList: [],
      nodeUserList: [],
      childNode: null,
    });
    for (let i = 0; i < nodeConfig.value.conditionNodes.length; i++) {
      nodeConfig.value.conditionNodes[i].error =
        conditionStr(nodeConfig.value, i) == '请设置条件' &&
        i != nodeConfig.value.conditionNodes.length - 1;
    }
    emit('update:nodeConfig', nodeConfig.value);
  };
</script>

<style lang="less" scoped>
  @import './index.less';
</style>
